------------------------------------------------------------------------------------------------------------------------------------------------
--[[
    本体遭到攻击后，会进入【不朽尸王】状态：每秒失去1.5理智，0.5体温，持续78秒（脱下也不能解除，穿着该衣服的时候再次被击会刷新时间至78秒，死亡会解除）。
    【不朽尸王】效果持续期间，移动系数增加0.3，攻击系数增加0.6，但不能睡觉（睡觉有台词）
    每次击杀怪物类单位，恢复10点体力值。
    【不朽尸王】状态内理智值或饱度降到10%以下的话立刻解除状态，并当场晕倒，下次醒来会进入【信】状态。
]]--
------------------------------------------------------------------------------------------------------------------------------------------------
---
    local DEBUFF_REMAIN_TIME = 78 -- 效果持续时间
------------------------------------------------------------------------------------------------------------------------------------------------
--- 素材
    local assets =
    {
        -- Asset("ANIM", "anim/cane.zip"),
        Asset( "IMAGE", "images/widgets/hutao_debuff_undying_lich_mask.tex" ),
        Asset( "ATLAS", "images/widgets/hutao_debuff_undying_lich_mask.xml" ),
    }
------------------------------------------------------------------------------------------------------------------------------------------------
--- debuff 激活
    local function OnAttached(inst,player) -- 玩家得到 debuff 的瞬间。 穿越洞穴、重新进存档 也会执行。
        inst.entity:SetParent(player.entity)
        inst.Transform:SetPosition(0,0,0)
        -----------------------------------------------------
        --- 计时器初始化
            if inst.components.hutao_data:Get("timer") == nil then
                inst.components.hutao_data:Set("timer",DEBUFF_REMAIN_TIME)
                player.components.hutao_com_inspect_data:Set("hutao_debuff_undying_lich",DEBUFF_REMAIN_TIME)
                inst.__timer:set(DEBUFF_REMAIN_TIME)
            end
            inst:DoPeriodicTask(1,function()
                local timer = inst.components.hutao_data:Add("timer",-1)
                player.components.hutao_com_inspect_data:Set("hutao_debuff_undying_lich",timer)
                if timer <= 0 then
                    inst:Remove()
                end
                inst.__timer:set(timer)
            end)
            inst:ListenForEvent("onremove",function()
                player.components.hutao_com_inspect_data:Set("hutao_debuff_undying_lich",0)
            end)
        -----------------------------------------------------
        --- 每秒效果
            inst:DoPeriodicTask(1,function()
                if player.components.sanity then
                    player.components.sanity:DoDelta(-1.5,true)
                end
                if player.components.temperature then
                    player.components.temperature:DoDelta(-0.5)
                end
                if player.components.locomotor then
                    player.components.locomotor:SetExternalSpeedMultiplier(inst,inst.prefab, 1+0.3)
                end
                if player.components.combat then
                    player.components.combat.externaldamagemultipliers:SetModifier(inst,1+0.6)
                end
                if player.components.hutao_com_near_danger then
                    player.components.hutao_com_near_danger:AddDanger(inst.prefab)
                end
            end)        
        -----------------------------------------------------
        --- 防止查理
            if player.components.grue ~= nil then
                player.components.grue:AddImmunity(inst.prefab)
            end
        -----------------------------------------------------
        --- 移除
            inst:ListenForEvent("onremove",function()
                player.components.hutao_com_near_danger:RemoveDanger(inst.prefab)
                if player.components.grue ~= nil then
                    player.components.grue:RemoveImmunity(inst.prefab)
                end
            end)
        -----------------------------------------------------
        --- 目标。周期性刷一下，避免无法启动。
            local function set_target_fn()
                inst.__target:set( inst.__target:value() == player and inst or player)
            end
            set_target_fn()
            inst:DoPeriodicTask(1,set_target_fn)            
        -----------------------------------------------------
        --- 周期性检查是否需要解除
            inst:DoPeriodicTask(0.5,function()
                if player.components.rider:IsRiding() then
                    inst:Remove()
                    return
                end
                if player.components.sanity:GetPercent() < 0.1 or player.components.hunger:GetPercent() < 0.1 then
                    inst:Remove()
                    player:PushEvent("hutao_event.getting_into_the_running.force_stop") -- 强制结束奔跑状态
                    -- print("fake error : sanity or hunger too low")
                    player.sg:GoToState("knockout")
                    local rest_time = inst.components.hutao_data:Add("timer",0)
                    local test_num = 100
                    local sleep_debuff = nil
                    local sleep_debuff_prefab = "hutao_debuff_undying_lich_sleep"
                    while test_num > 0 do
                        sleep_debuff = player:GetDebuff(sleep_debuff_prefab)
                        if sleep_debuff and sleep_debuff:IsValid() then
                            break
                        end
                        player:AddDebuff(sleep_debuff_prefab,sleep_debuff_prefab)
                        test_num = test_num - 1
                    end
                    if sleep_debuff ~= nil then
                        sleep_debuff:PushEvent("SetTime",rest_time)
                    end
                end                
            end)
        -----------------------------------------------------
        --- 每次击杀怪物类单位，恢复10点体力值。
            inst:ListenForEvent("killed",function(_,_table)
                local killed_target = _table and _table.victim
                if killed_target and killed_target:HasTag("monster") then
                    player.components.hutao_com_physical_power:DoDelta(10)
                end
            end,player)
        -----------------------------------------------------
        -- 死亡清除
            inst:ListenForEvent("death",function()
                inst:Remove()
            end,player)
        -----------------------------------------------------
    end

    local function ExtendDebuff(inst) --- 重复得到debuff的瞬间
        inst.components.hutao_data:Set("timer",DEBUFF_REMAIN_TIME)
    end
------------------------------------------------------------------------------------------------------------------------------------------------
--- hud mask
    local function create_buff_mask_in_client_side(inst)
        -----------------------------------------------------
        --- 预检查 和 模块引入
            local Widget = require "widgets/widget"
            local Image = require "widgets/image"
            local Text = require "widgets/text"
        -----------------------------------------------------
        --- 根节点
            local front_root = ThePlayer.HUD
            local root = front_root:AddChild(Widget())
            root:SetHAnchor(0) -- 设置原点x坐标位置，0、1、2分别对应屏幕中、左、右
            root:SetVAnchor(0) -- 设置原点y坐标位置，0、1、2分别对应屏幕中、上、下
            root:SetPosition(0,0)
            -- root:MoveToFront()
            root:MoveToBack()
            root:SetScaleMode(SCALEMODE_FIXEDSCREEN_NONDYNAMIC)   --- 缩放模式
            root:SetClickable(false)
        -----------------------------------------------------
        ---
        -----------------------------------------------------
        --- 图层
            local img = root:AddChild(Image())
            img:SetTexture("images/widgets/hutao_debuff_undying_lich_mask.xml","hutao_debuff_undying_lich_mask.tex")
            -- local scale = 2.2
            -- img:SetScale(scale,scale,scale)
            img:SetFadeAlpha(0.7)
        -----------------------------------------------------
        --- 文本
            local time_str = root:AddChild(Text(CODEFONT,40,"",{ 255/255 , 0/255 ,0/255 , 1}))
            local time_pt = Vector3(-200,320,0)
            time_str:SetPosition(time_pt.x,time_pt.y)
        -----------------------------------------------------
        --- 
            root.inst:ListenForEvent("timer_update",function()
                local time = inst.__timer:value()
                time_str:SetString(tostring(inst:GetDisplayName()).." : ".. tostring(time))
            end,inst)
        -----------------------------------------------------
        --- 移除
            root.inst:ListenForEvent("onremove",function()
                root:Kill()
            end,inst)
        -----------------------------------------------------
        ---
            return root
        -----------------------------------------------------
    end
    local function create_fake_light_in_client_side(parent)
        local inst = CreateEntity()
        inst.entity:AddTransform()
        inst.entity:AddLight()        
        inst.Light:SetFalloff(0.1)
        inst.Light:SetIntensity(.7)
        inst.Light:SetRadius(3)
        inst.Light:SetColour(180 / 255, 195 / 255, 150 / 255)
        inst.entity:SetParent(parent.entity)
        return inst
    end
    local function create_mask(inst)
        if inst.__hud_mask == nil then
            inst.__hud_mask = create_buff_mask_in_client_side(inst)
        end
        if inst.__fake_light == nil then
            inst.__fake_light = create_fake_light_in_client_side(inst)
        end
    end
    local function hud_mask_install(inst)
        local link_entity = inst.__target:value()
        if link_entity == ThePlayer and ThePlayer and ThePlayer.HUD then
            create_mask(inst)
        end
    end
------------------------------------------------------------------------------------------------------------------------------------------------
--- 实体
    local function fn()
        local inst = CreateEntity()

        inst.entity:AddTransform()
        inst.entity:AddNetwork()
        inst.entity:AddTransform()

        inst:AddTag("CLASSIFIED")

        inst.entity:SetPristine()
        inst.__target = net_entity(inst.GUID,"hutao_debuff_undying_lich.target","linked_player")
        inst.__timer = net_float(inst.GUID,"hutao_debuff_undying_lich.timer","timer_update")
        if not TheNet:IsDedicated() then
            inst:ListenForEvent("linked_player",hud_mask_install)
        end
        if not TheWorld.ismastersim then
            return inst
        end

        inst:AddComponent("hutao_data")
        inst:AddComponent("debuff")
        inst.components.debuff:SetAttachedFn(OnAttached)
        inst.components.debuff.keepondespawn = true -- 是否保持debuff 到下次登陆
        inst.components.debuff:SetExtendedFn(ExtendDebuff)

        return inst
    end
------------------------------------------------------------------------------------------------------------------------------------------------

return Prefab("hutao_debuff_undying_lich", fn,assets)
